<?php
declare (strict_types = 1);

namespace app\api\middleware;

use tinywan\Jwt;
use tinywan\exception\JWTTokenExpiredException;
use think\exception\HttpResponseException;
class LoginCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //要忽略的控制器方法
        $ignore_controller = ['Auth'];
        $controller = $request->controller();
        if(!in_array($controller, $ignore_controller))
        {
            try{
                //$user_info = Jwt::getUser(); //（1）查询数据库数据

                $user_info = Jwt::getExtend(); //（2）只解析token数据
                if(empty($user_info))
                {
                    throw new HttpResponseException(returnJson(401, '认证失败，请重新登录'));
                }else{

                    $request->user_info = $user_info;
                }
            } catch (JwtTokenExpiredException $e){

                throw new HttpResponseException(returnJson(401, '认证已过期请重新登录'));

            } catch(\Exception $e) {

                throw new HttpResponseException(returnJson(401, '认证失败，请重新登录'));
            }
        }
        return $next($request);
    }
}
